#region Using

using System;
using System.Text;
using System.Text.RegularExpressions;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;
using System.Web;

#endregion

[Extension("Append FeedFlare script at the end of posts and pages", "1.0", "Cristiano Fino")]
public class FeedFlare
{
	public FeedFlare()
	{
		Post.Serving += new EventHandler<ServingEventArgs>(Serving);
        Page.Serving += new EventHandler<ServingEventArgs>(Serving);
	}

    /// <summary>
	/// Definition of FeedFlare script
	/// </summary>
    private const string FeedBurnerScript = "<script src=\"http://feeds.feedburner.com/~s/{0}?i={1}\" type=\"text/javascript\" charset=\"utf-8\"></script>";


	/// <summary>
	/// If exist FeedBurner's alternative feed url then create and append FeedFlare script
	/// </summary>
	private static void Serving(object sender, ServingEventArgs e)
	{
		if (BlogSettings.Instance.AlternateFeedUrl != "")
        {
            if (e.Location == ServingLocation.SinglePage || e.Location == ServingLocation.SinglePost || e.Location == ServingLocation.PostList)
            {
                string FeedBurnerUrl = BlogSettings.Instance.AlternateFeedUrl;
                string AbsoluteUrl = "";
                if (e.Location == ServingLocation.SinglePage)
                { 
                    Page post = (Page)sender; 
                    AbsoluteUrl = post.AbsoluteLink.ToString();
                }
                else { 
                    Post post = (Post)sender;
                    AbsoluteUrl = post.AbsoluteLink.ToString();
                }
                if (FeedBurnerUrl.EndsWith("/")) FeedBurnerUrl = FeedBurnerUrl.Remove(FeedBurnerUrl.Length - 1);
                string FeedBurnerUsername = FeedBurnerUrl.Substring(FeedBurnerUrl.LastIndexOf("/") + 1);
                e.Body = e.Body + string.Format(FeedBurnerScript, FeedBurnerUsername, AbsoluteUrl);
            }
        }
	}

}
